﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SmartMathLibrary.LinearEquationSolvers;

namespace SmartMathLibrary.NonlinearEquationSolvers
{
    /// <summary>
    /// This class provides the solving of a complex nonlinear system of equation by using the 
    /// extended Newton method in a complex version.
    /// </summary>
    [Serializable]
    public class NewtonComplexNonLinearSystemSolver : AbstractComplexNonLinearSystemSolver
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="NewtonComplexNonLinearSystemSolver"/> class.
        /// </summary>
        /// <param name="equationSystem">The complex nonlinear system of equation to solve.</param>
        public NewtonComplexNonLinearSystemSolver(ComplexNonLinearEquationSystem equationSystem)
            : base(equationSystem)
        {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="NewtonComplexNonLinearSystemSolver"/> class.
        /// </summary>
        /// <param name="equationSystemFunctions">The complex nonlinear system of equation to solve.</param>
        public NewtonComplexNonLinearSystemSolver(HardMultivariateComplexFunction[] equationSystemFunctions)
            : base(equationSystemFunctions)
        {
        }

        /// <summary>
        /// Solves the complex nonlinear system of equation by using the extended Newton method 
        /// in a complex version. The property PrecisionError have to be checked after the 
        /// calculation to be sure that the results are correct.
        /// </summary>
        /// <param name="startValues">The start values for the calculation.</param>
        /// <param name="iterations">The maximum number of iterations.</param>
        /// <param name="precision">The precision of the result.</param>
        /// <returns>
        /// The approximated numeric results, which solves the complex nonlinear system of
        /// equation.
        /// </returns>
        public override GeneralComplexVector SolveNonLinearSystem(GeneralComplexVector startValues, int iterations,
                                                                  double precision)
        {
            if (startValues == (GeneralComplexVector) null)
            {
                throw new ArgumentNullException("startValues");
            }

            if (startValues.Count != this.EquationSystem.EquationSystem.Length)
            {
                throw new ArgumentException(
                    "The number of components in the start vector has to be even with the number of equations.");
            }

            if (this.EquationSystem.EquationSystem.Length < 2)
            {
                throw new ArgumentException(
                    "The system of equation has to have to contain a minimum number of two equations.");
            }

            int iterationCount = 0;
            ComplexNumber tempuri;
            GeneralComplexVector result = startValues.Copy();
            GeneralComplexVector parameterVector = new GeneralComplexVector(this.EquationSystem.EquationSystem.Length);
            ComplexMatrix jacobianMatrix = new ComplexMatrix(this.EquationSystem.EquationSystem.Length,
                                                             this.EquationSystem.EquationSystem.Length);

            while (iterationCount < iterations)
            {
                GeneralComplexVector functionResult = this.EquationSystem.SolveAt(result);

                for (int i = 0; i < this.EquationSystem.EquationSystem.Length; i++)
                {
                    ComplexNumber delta;

                    tempuri = result[i];

                    if (Math.Abs(tempuri.RealNumberPart) > 1.0)
                    {
                        delta = tempuri * precision;
                    }
                    else
                    {
                        delta = new ComplexNumber(precision, precision);
                    }

                    result[i] = tempuri + delta;
                    parameterVector = this.EquationSystem.SolveAt(result);
                    result[i] = tempuri;

                    for (int j = 0; j < this.EquationSystem.EquationSystem.Length; j++)
                    {
                        jacobianMatrix.SetValueAtPosition(j, i, (parameterVector[j] - functionResult[j]) / delta);
                    }
                }

                for (int i = 0; i < this.EquationSystem.EquationSystem.Length; i++)
                {
                    tempuri = new ComplexNumber(0.0);

                    for (int j = 0; j < this.EquationSystem.EquationSystem.Length; j++)
                    {
                        tempuri += jacobianMatrix.GetValueAtPosition(i, j) * result[j];
                    }

                    parameterVector[i] = tempuri - functionResult[i];
                }

                double dtmp = 0.0;
                GaussComplexLinearSystemSolver linearSystemSolver = new GaussComplexLinearSystemSolver(jacobianMatrix,
                                                                                                       parameterVector);
                GeneralComplexVector x0 = linearSystemSolver.SolveLinearSystem();

                for (int i = 0; i < this.EquationSystem.EquationSystem.Length; i++)
                {
                    dtmp += Math.Abs((x0[i] - result[i]).RealNumberPart);
                    result[i] = x0[i];
                }

                if (dtmp < 1e-4)
                {
                    break;
                }

                iterationCount++;
            }

            this.neededIterations = iterationCount;
            this.precisionError = (iterations == iterationCount);

            return result;
        }
    }
}